<template>
  <div id="root">
    <div class="todo-container">
      <div class="todo-wrap">
        <MyHeader @addTodo="addTodo"></MyHeader>
        <MyList
          :todos="todos"
          :checkTodo="checkTodo"
          :deleteTodo="deleteTodo"
        ></MyList>
        <MyFooter
          :todos="todos"
          @checkAllTodo="checkAllTodo"
          @clearAllTodo="clearAllTodo"
        ></MyFooter>
      </div>
    </div>
  </div>
</template>

<script>
import MyHeader from "./components/MyHeader.vue";
import MyList from "./components/MyList.vue";
import MyFooter from "./components/MyFooter.vue";

export default {
  name: "App",
  components: { MyHeader, MyList, MyFooter },
  data() {
    return {
      /* 在读取时从本地获取；若是第一次，因为本地没有todos，则直接设为空数组
      后面再监听时，发生改变会直接将数组存进去。 */
      todos: JSON.parse(localStorage.getItem("todos")) || [],
    };
  },
  methods: {
    // 添加一个todo
    addTodo(todoObj) {
      this.todos.unshift(todoObj);
    },

    // 勾选or取消勾选
    checkTodo(id) {
      this.todos.forEach((item) => {
        if (item.id == id) item.done = !item.done;
      });
    },

    // 删除一个todo
    deleteTodo(id) {
      this.todos = this.todos.filter((item) => {
        return item.id != id;
      });
    },

    // 全选or全不选
    checkAllTodo(done) {
      this.todos.forEach((item) => {
        item.done = done;
      });
    },

    // 清除所有已经完成的todo
    clearAllTodo() {
      this.todos = this.todos.filter((item) => item.done == false);
    },
  },
  watch: {
    // 简写的监视，只监视数组第一层是否发生变化
    // 开启深度监视，这样在更改数组里的某一项对象里的属性时，可以检测到
    todos: {
      deep: true,
      handler(newVal) {
        localStorage.setItem("todos", JSON.stringify(newVal));
      },
    },
  },
};
</script>

<style>
/*base*/
body {
  background: #fff;
}

.btn {
  display: inline-block;
  padding: 4px 12px;
  margin-bottom: 0;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2),
    0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.btn-danger {
  color: #fff;
  background-color: #da4f49;
  border: 1px solid #bd362f;
}
.btn-edit {
  color: #000;
  background-color: skyblue;
  border: 1px solid aquamarine;
  margin-right: 10px;
}

.btn-edit:hover {
  background-color: rgb(7, 183, 253);
}

.btn-danger:hover {
  color: #fff;
  background-color: #bd362f;
}

.btn:focus {
  outline: none;
}

.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>
